import React, { useState, useEffect } from 'react'
import { FileText, Clock, Hash } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { ChatService } from '@/services/chatService'

interface ConversationSummary {
  id: number
  conversation_id: number
  summary_content: string
  start_message_seq: number
  end_message_seq: number
  summary_type: string
  created_at: string
}

interface ConversationSummaryProps {
  conversationId: string | undefined
  isVisible: boolean
  onClose: () => void
}

export function ConversationSummaryComponent({
  conversationId,
  isVisible,
  onClose
}: ConversationSummaryProps) {
  const [summaries, setSummaries] = useState<ConversationSummary[]>([])
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const chatService = ChatService.getInstance()

  useEffect(() => {
    if (isVisible && conversationId && conversationId !== 'unknown') {
      loadSummaries()
    }
  }, [isVisible, conversationId])

  const loadSummaries = async () => {
    if (!conversationId || conversationId === 'unknown') return
    
    setIsLoading(true)
    setError(null)
    
    try {
      const summaryData = await chatService.getConversationSummaries(parseInt(conversationId))
      setSummaries(summaryData)
    } catch (error) {
      console.error('Error loading summaries:', error)
      setError('Failed to load conversation summaries')
    } finally {
      setIsLoading(false)
    }
  }

  if (!isVisible) return null

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <Card className="w-full max-w-2xl max-h-[80vh] overflow-hidden">
        <CardHeader className="border-b">
          <div className="flex items-center justify-between">
            <CardTitle className="flex items-center gap-2">
              <FileText className="w-5 h-5" />
              Conversation Summaries
            </CardTitle>
            <Button variant="outline" size="sm" onClick={onClose}>
              Close
            </Button>
          </div>
        </CardHeader>
        
        <CardContent className="p-0">
          <div className="max-h-[60vh] overflow-y-auto p-4">
            {isLoading ? (
              <div className="flex items-center justify-center py-8">
                <div className="text-muted-foreground">Loading summaries...</div>
              </div>
            ) : error ? (
              <div className="flex items-center justify-center py-8">
                <div className="text-red-500">{error}</div>
              </div>
            ) : summaries.length === 0 ? (
              <div className="flex items-center justify-center py-8">
                <div className="text-muted-foreground">
                  No summaries available for this conversation (ID: {conversationId})
                  <br />
                  <small>Debug: Loaded {summaries.length} summaries</small>
                </div>
              </div>
            ) : (
              <div className="space-y-4">
                {summaries.map((summary) => (
                  <Card key={summary.id} className="border">
                    <CardContent className="p-4">
                      <div className="flex items-start justify-between mb-2">
                        <div className="flex items-center gap-2 text-sm text-muted-foreground">
                          <Hash className="w-4 h-4" />
                          <span>Messages {summary.start_message_seq}-{summary.end_message_seq}</span>
                          <span className="px-2 py-1 bg-secondary rounded text-xs">
                            {summary.summary_type}
                          </span>
                        </div>
                        <div className="flex items-center gap-1 text-xs text-muted-foreground">
                          <Clock className="w-3 h-3" />
                          {new Date(summary.created_at).toLocaleString()}
                        </div>
                      </div>
                      <div className="text-sm leading-relaxed">
                        {summary.summary_content}
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            )}
          </div>
        </CardContent>
      </Card>
    </div>
  )
}